import { createRouter, createWebHashHistory } from 'vue-router'

const Login = ()=>import("views/Login");
const Register = ()=>import("views/Register");
const MainPage = ()=>import('views/MainPage');
const NotFoundComponent = ()=>import("components/NotFoundComponent")

const routes = [
  {
    path: '',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/register',
    component: Register
  },
  {
    path: '/mainPage',
    component: MainPage
  },
  {
    path: '/404',
    name: '404',
    component: NotFoundComponent
  },
  {
    path: '/:pathMatch(.*)',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to,from,next)=>{
  if(to.path == '/MainPage' && sessionStorage.getItem('userName') == null){
    next('/');
  }
  else if(to.path == '/login' && sessionStorage.getItem('userName') != null){
    next('/MainPage');
  }
  else{
    next();
  }
});

export default router
